﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Globalization;
using System.Linq;
using System.Windows.Forms;
using ExtendedDal;
using SD.LLBLGen.Pro.ORMSupportClasses;
using WHMS.EntityClasses;
using WHMS.HelperClasses;
using WMS.HelperClasses;

namespace WMS
{
    public partial class ExaminationDocument : Form
    {
        #region Screen

        private ExamineDoc _examineDoc;
        private SupplyOrderEntity _supplyOrderEntity;
        private TransferRequestEntity _transferRequestEntity;

        public ExaminationDocument()
        {
            InitializeComponent();

            _examineDoc = new ExamineDoc();
        }

        #endregion

        #region Events
        private void _btnSearchTransferRequest_Click(object sender, EventArgs e)
        {
            var filter = new RelationPredicateBucket(StorekeeperFields.KeeperId == Business.GetCurrentUserId());
            filter.Relations.Add(TransferRequestEntity.Relations.ProjectEntityUsingProjectId);
            filter.Relations.Add(TransferRequestEntity.Relations.StoreEntityUsingFromStoreId);
            filter.Relations.Add(StoreEntity.Relations.StorekeeperEntityUsingStoreId);

            var searchForm = new SearchForm(TransferRequestFields.RequestNumber, TransferRequestFields.ProjectId, TransferRequestFields.Date, filter, () => Business.GetRunningProjects());
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                _txtTransferRequest.Text = searchForm.SelectedNumber;
                ResetSupplyOrder();
                RetrieveRequest();
            }
        }

        private void _btnRetrieveTransfer_Click(object sender, EventArgs e)
        {
            ResetSupplyOrder();
            RetrieveRequest();
        }
        private void SaveBtn_Click(object sender, EventArgs e)
        {
            try
            {
                if (!IsValidGrid()) return;

                using (var extendedDataContext = new ExtendedDataContext())
                {
                    if (_examineDoc != null && _examineDoc.Id <= 0)
                    {
                        MapToEntity(_examineDoc);
                        if (string.IsNullOrEmpty(_examineDoc.Serial))
                        {
                            ExamineSerialError.SetError(_txtSerial, "يجب كتابة رقم محضر الفحص");
                            return; // prevent saving
                        }

                        if (!IsValidQuantity(_examineDoc)) return;

                        extendedDataContext.ExamineDocs.InsertOnSubmit(_examineDoc);
                        extendedDataContext.SubmitChanges();
                    }
                    else
                    {
                        var entity = extendedDataContext.ExamineDocs.Where(x => x.Id == _examineDoc.Id).SingleOrDefault();
                        MapToEntity(entity);
                        if (string.IsNullOrEmpty(entity.Serial))
                        {
                            ExamineSerialError.SetError(_txtSerial, "يجب كتابة رقم محضر الفحص");
                            return; // prevent saving
                        }

                        if (!IsValidQuantity(_examineDoc)) return;

                        extendedDataContext.SubmitChanges();
                    }
                    MessageBox.Show(@"تم الحفظ بنجاح.");
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
            }
        }

        private void SearchBtn_Click(object sender, EventArgs e)
        {
            ResetTransferRequest();
            SearchSupplyOrder();
        }
        private void btnSearchExamineDoc_Click(object sender, EventArgs e)
        {
            SearchExamineDoc searchForm = _supplyOrderEntity == null
                                              ? new SearchExamineDoc()
                                              : new SearchExamineDoc(_supplyOrderEntity.Id,false);

            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                using (var context = new ExtendedDataContext())
                {
                    var examineEntity =
                        context.ExamineDocs.Where(x => x.Serial == searchForm.SelectedNumber).FirstOrDefault();

                    if (examineEntity != null)
                    {
                        _examineDoc = examineEntity;
                        GetExamineForSupplyOrder(context);
                        GetExamineForTransferRequest(context);
                    }
                }
            }
        }

        private void dtpDate_ValueChanged(object sender, EventArgs e)
        {
            // Using Arabic-Egyptian culture to show days in arabic language
            var culture = new CultureInfo("ar-EG");
            var dateTimeFormat = culture.DateTimeFormat;
            _txtWeekDay.Text = dateTimeFormat.GetAbbreviatedDayName(dtpDate.Value.DayOfWeek);
        }

        private void _btnDelete_Click(object sender, EventArgs e)
        {
            var form = new DeleteConfirmationForm();

            if (form.ShowDialog() == DialogResult.Yes)
            {
                using (var context = new ExtendedDataContext())
                {
                    if (_examineDoc == null) return;

                    var entityItems = context.ExamineDocItems.Where(i => i.ExamineDocId == _examineDoc.Id).ToList();
                    context.ExamineDocItems.DeleteAllOnSubmit(entityItems);
                    var entity = context.ExamineDocs.Where(x => x.Id == _examineDoc.Id).FirstOrDefault();
                    context.ExamineDocs.DeleteOnSubmit(entity);
                    context.SubmitChanges();
                    ResetForm();
                }
            }
        }
        private void _btnNewExamineDoc_Click(object sender, EventArgs e)
        {
            ResetForm();
        }
        /// <summary>
        /// If clicked on btn retrieve
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void _btnRetrieveExamine_Click(object sender, EventArgs e)
        {
            using (var context = new ExtendedDataContext())
            {
                var examineEntity =
                    context.ExamineDocs.Where(x => x.Serial == _txtSerial.Text).FirstOrDefault();

                if (examineEntity != null)
                {
                    // if the entered code for examine is not related to the current supply order
                    if (_supplyOrderEntity != null && examineEntity.SupplyOrderId != _supplyOrderEntity.Id)
                    {
                        _txtSerial.Text = string.Empty;
                        MessageBox.Show("محضر الفحص المطلوب مختص بامر توريد مختلف");
                        return;
                    }

                    _examineDoc = examineEntity;

                    GetExamineForSupplyOrder(context);
                    GetExamineForTransferRequest(context);
                }
            }
        }
        private void _btnRetrieveOrder_Click(object sender, EventArgs e)
        {
            ResetTransferRequest();
            RetrieveOrder();
        }

        #endregion

        #region Grid Events


        private void _dgvItems_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            if (!IsValidExamineQuantity(_dgvItems.Rows[e.RowIndex]))
            {
                _dgvItems.Rows[e.RowIndex].Cells[_colQuantityAfterExamine.Index].ErrorText =
                    "الكمية بعد الفحص لا يمكن ان تكون اكبر من قبل الفحص";
            }
            else
            {
                _dgvItems.Rows[e.RowIndex].Cells[_colQuantityAfterExamine.Index].ErrorText = "";
            }
            ExamineSerialError.SetError(_dgvItems, _dgvItems.Rows[e.RowIndex].Cells[_colQuantityAfterExamine.Index].ErrorText);
        }

        private void _dgvItems_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0)
                return;

            if (e.ColumnIndex == _dgvItems.Columns["_colQuantityAfterExamine"].Index)
            {
                SetWeightAfterExamine((decimal)_dgvItems.Rows[e.RowIndex].Cells["_colQuantityWeight"].Value,
                                      (decimal)_dgvItems.Rows[e.RowIndex].Cells["_colQuantity"].Value,
                                      (decimal)_dgvItems.Rows[e.RowIndex].Cells["_colQuantityAfterExamine"].Value,
                                      e.RowIndex);
            }
        }
        #endregion

        #region Private Methods

        private bool IsValidQuantity(ExamineDoc doc)
        {
            if (doc.ExamineDocItems.Sum(d => d.Quantity) <= 0)
            {
                ExamineSerialError.SetError(_dgvItems, "الكمية لا يمكن ان تكون صفراً");
                return false;
            }
            else
            {
                ExamineSerialError.SetError(_dgvItems, "");
                return true;
            }
        }

        private void ResetSupplyOrder()
        {
            _supplyOrderEntity = null;
            _dtpSupplyOrderDate.Value = DateTime.Now;
            _txtVendor.Text = "";
            _txtSupplyOrderNumber.Text = "";
            _txtProject.Text = "";
        }

        private void ResetTransferRequest()
        {
            _transferRequestEntity = null;
            _dtpTransferDate.Value = DateTime.Now;
            _txtFromProject.Text = "";
            _txtToProject.Text = "";
            _txtFromStore.Text = "";
            _txtToStore.Text = "";
            _txtTransferRequest.Text = "";
        }

        private void GetExamineForSupplyOrder(ExtendedDataContext context)
        {
            MapToForm();

            // Get supply if Examination was chosen
            SupplyOrderEntity supplyOrderEntity = Business.GetSupplyOrderByIdOrNumber
                (id: _examineDoc.SupplyOrderId.HasValue ? _examineDoc.SupplyOrderId.Value : 0);

            if (supplyOrderEntity != null)
            {
                _txtSupplyOrderNumber.Text = supplyOrderEntity.SupplyOrderNumber;
                _dtpSupplyOrderDate.Value = supplyOrderEntity.Date;

                var supplyOrderItems = new EntityCollection<SupplyOrderItemEntity>();

                DALHelper.FetchCollection
                    (supplyOrderItems, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == supplyOrderEntity.Id));

                var docs = context.ExamineDocs.Where(t => t.SupplyOrderId == supplyOrderEntity.Id).ToList();
                var acceptedDocs = context.ExamineDocs.Where
                    (t => t.SupplyOrderId == supplyOrderEntity.Id && t.IsAccepted.HasValue && t.IsAccepted.Value).ToList();

                var items = _examineDoc.ExamineDocItems.Select(x =>
                                                    new ExamineDocView
                                                    {
                                                        ItemId = x.ItemId,
                                                        ItemName = Business.GetItemDetails(x.ItemId).Rows[0]["Name"],
                                                        Quantity = supplyOrderItems.Where(i => i.ItemId == x.ItemId).FirstOrDefault().Quantity,
                                                        QuantityWeight = supplyOrderItems.Where(i => i.ItemId == x.ItemId).FirstOrDefault().Quantity
                                                        * decimal.Parse(Business.GetItemDetails(x.ItemId).Rows[0]["Weight"].ToString()),
                                                        QuantityAfterExamine = x.Quantity,
                                                        QuantityAfterExamineWeight = x.Quantity * decimal.Parse(Business.GetItemDetails(x.ItemId).Rows[0]["Weight"].ToString()),
                                                        Vendor = Business.GetSupplyOrderSupplierName(supplyOrderEntity.Id),
                                                        Comments = Business.GetItemDescription(x.ItemId),
                                                        Unit = Business.GetItemDetails(x.ItemId).Rows[0]["Unit"],
                                                        LastExaminedAcceptedQuantity = (acceptedDocs != null && acceptedDocs.Count > 0) ?
                                                                                       acceptedDocs.SelectMany(t => t.ExamineDocItems
                                                                                       .Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0,
                                                        LastExaminedQuantity = (docs != null && docs.Count > 0) ?
                                                        docs.SelectMany(t => t.ExamineDocItems.Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0
                                                    }).ToList();

                _dgvItems.DataSource = items;
            }
            else
            {
                _txtSupplyOrderNumber.Text = string.Empty;
            }
        }

        private void GetExamineForTransferRequest(ExtendedDataContext context) 
        {
            MapToForm();

            // Get Transfer  if Examination was chosen
            _transferRequestEntity = Business.GetTransferRequestByIdOrNumber
                (id: _examineDoc.TransferRequestId.HasValue ? _examineDoc.TransferRequestId.Value : 0);

            if (_transferRequestEntity != null)
            {
                _txtTransferRequest.Text = _transferRequestEntity.RequestNumber;
                _dtpTransferDate.Value = _transferRequestEntity.Date;

                var transferRequestItems = new EntityCollection<TransferRequestItemEntity>();

                DALHelper.FetchCollection
                    (transferRequestItems, new RelationPredicateBucket(TransferRequestItemFields.TransferRequestId == _transferRequestEntity.Id));

                var docs = context.ExamineDocs.Where(t => t.TransferRequestId == _transferRequestEntity.Id).ToList();
                var acceptedDocs = context.ExamineDocs.Where
                    (t => t.TransferRequestId == _transferRequestEntity.Id && t.IsAccepted.HasValue && t.IsAccepted.Value).ToList();

                var items = _examineDoc.ExamineDocItems.Select(x =>
                                                    new ExamineDocView
                                                    {
                                                        ItemId = x.ItemId,
                                                        ItemName = Business.GetItemDetails(x.ItemId).Rows[0]["Name"],
                                                        Quantity = transferRequestItems.Where(i => i.ItemId == x.ItemId).FirstOrDefault().Quantity,
                                                        QuantityWeight = transferRequestItems.Where(i => i.ItemId == x.ItemId).FirstOrDefault().Quantity
                                                        * decimal.Parse(Business.GetItemDetails(x.ItemId).Rows[0]["Weight"].ToString()),
                                                        QuantityAfterExamine = x.Quantity,
                                                        QuantityAfterExamineWeight = x.Quantity * decimal.Parse(Business.GetItemDetails(x.ItemId).Rows[0]["Weight"].ToString()),
                                                        Vendor = "",
                                                        Comments = Business.GetItemDescription(x.ItemId),
                                                        Unit = Business.GetItemDetails(x.ItemId).Rows[0]["Unit"],
                                                        LastExaminedAcceptedQuantity = (acceptedDocs != null && acceptedDocs.Count > 0) ?
                                                                                       acceptedDocs.SelectMany(t => t.ExamineDocItems
                                                                                       .Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0,
                                                        LastExaminedQuantity = (docs != null && docs.Count > 0) ?
                                                        docs.SelectMany(t => t.ExamineDocItems.Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0
                                                    }).ToList();

                _dgvItems.DataSource = items;

                SetProjectsAndStores();
            }
            else
            {
                _txtTransferRequest.Text = string.Empty;
            }
        }

        private bool HandleColumnsValidation(DataGridViewRow row, decimal itemOldQty)
        {
            // If qty after examine is more than then invalid Qty
            var x = (decimal)(row.Cells["_colQuantityAfterExamine"].Value);
            var y = (decimal)(row.Cells["_colLastExaminedQuantity"].Value);
            var z = (decimal)(row.Cells["_colQuantity"].Value);

            // Handle unknown exception
            if (y > z)
                y = z;

            if ((x - itemOldQty) + y > z)
                return false;
            return true;
        }

        private bool IsValidExamineQuantity(DataGridViewRow row)
        {
            try
            {
                // in case of changing qty for last examine doc in one supply order
                // if SO has 200 item and last ED used all then after retrieving it and trying to change will validate as false
                // so getting old Qty to subtract it from existing one
                if (_examineDoc != null)
                {
                    var itemId = (int)row.Cells["_colItemId"].Value;
                    var item = _examineDoc.ExamineDocItems.Where(t => t.ItemId == itemId).FirstOrDefault();

                    decimal oldQty = 0;
                    
                    if (item != null)
                    {
                        oldQty = item.Quantity;
                    }
                    
                    return HandleColumnsValidation(row, oldQty);
                }

                // in all case except the above one
                return HandleColumnsValidation(row, 0);
            }
            catch
            {
                return false; // no values in at least one cell
            }
        }

        /// <summary>
        /// Prevent saving if any invalid row
        /// </summary>
        /// <returns></returns>
        private bool IsValidGrid()
        {
            foreach (DataGridViewRow row in _dgvItems.Rows)
            {
                if (!IsValidExamineQuantity(row))
                    return false;
            }

            return true;
        }

        private void MapGridToEntity(ExamineDoc examineDoc)
        {
            var examineItems = new EntitySet<ExamineDocItem>();
            if (examineDoc.ExamineDocItems == null || examineDoc.ExamineDocItems.Count <= 0)
            {
                foreach (DataGridViewRow row in _dgvItems.Rows)
                {
                    //if (!IsValidExamineQuantity(row))
                    //    throw new Exception("الكمية بعد الفحص لا يمكن ان تكون اكبر من قبل الفحص");
                    examineItems.Add(new ExamineDocItem
                                         {
                                             ExamineDocId = examineDoc.Id,
                                             ItemId = (int)(row.Cells["_colItemId"].Value),
                                             Quantity = (decimal)(row.Cells["_colQuantityAfterExamine"].Value),
                                         });
                }

                examineDoc.ExamineDocItems = examineItems;
            }
            else
            {
                for (int index = 0; index < _dgvItems.Rows.Count; index++)
                {
                    DataGridViewRow row = _dgvItems.Rows[index];

                    //if (!IsValidExamineQuantity(row))
                    //    throw new Exception("الكمية بعد الفحص لا يمكن ان تكون اكبر من قبل الفحص");
                    examineDoc.ExamineDocItems[index].ExamineDocId = examineDoc.Id;
                    examineDoc.ExamineDocItems[index].ItemId = (int)(row.Cells["_colItemId"].Value);
                    examineDoc.ExamineDocItems[index].Quantity = (decimal)(row.Cells["_colQuantityAfterExamine"].Value);
                }
            }
        }

        /// <summary>
        /// Must have parameter for this object as submit changes in linq needs tracked entity
        /// </summary>
        /// <param name="examineDoc"></param>
        private void MapToEntity(ExamineDoc examineDoc)
        {
            if (examineDoc == null) return;

            if (_supplyOrderEntity == null)
            {
                // Get supply if Examination was chosen
                _supplyOrderEntity = Business.GetSupplyOrderByIdOrNumber(id: _examineDoc.SupplyOrderId.HasValue ?
                    _examineDoc.SupplyOrderId.Value : 0);
            }

            if (_transferRequestEntity == null)
            {
                // Get transfer if Examination was chosen
                _transferRequestEntity = Business.GetTransferRequestByIdOrNumber(id: _examineDoc.TransferRequestId.HasValue ? 
                    _examineDoc.TransferRequestId.Value : 0);
            }
            examineDoc.CreationDate = dtpDate.Value;
            examineDoc.IsAccepted = rBtnAcceptItems.Checked;
            examineDoc.IsMatched = rBtnMatched.Checked;

            //examineDoc.OperationName = string.IsNullOrEmpty(_txtOperation.Text) ? "" : _txtOperation.Text.Trim();
            examineDoc.Serial = string.IsNullOrEmpty(_txtSerial.Text) ? "" : _txtSerial.Text.Trim();
            examineDoc.SupplyOrderId = _supplyOrderEntity != null ? _supplyOrderEntity.Id : (int?)null;
            examineDoc.TransferRequestId = _transferRequestEntity != null ? _transferRequestEntity.Id : (int?)null;

            MapGridToEntity(examineDoc);
        }

        private void MapToForm()
        {
            if (_examineDoc == null) return;

            dtpDate.Value = _examineDoc.CreationDate;
            if (_examineDoc.IsAccepted == true)
                rBtnAcceptItems.Checked = true;
            else
                rBtnRefuseItems.Checked = true;

            if (_examineDoc.IsMatched == true)
                rBtnMatched.Checked = true;
            else
                rBtnNotMatched.Checked = true;

            _txtSerial.Text = _examineDoc.Serial;

            ToggleGridEditing();
        }

        private void ResetForm()
        {
            _supplyOrderEntity = null;
            _transferRequestEntity = null;
            _examineDoc = new ExamineDoc();

            dtpDate.Value = DateTime.Now;
            rBtnAcceptItems.Checked = true;
            rBtnRefuseItems.Checked = false;
            rBtnMatched.Checked = true;
            rBtnNotMatched.Checked = false;
            _txtSerial.Text = string.Empty;
            
            _dgvItems.DataSource = new List<ExamineDocView>();

            RetrieveOrder();
            RetrieveRequest();

            ToggleGridEditing();
        }

        private void RetrieveOrder()
        {
            if (string.IsNullOrEmpty(_txtSupplyOrderNumber.Text.Trim()))
                return;

            var collection = new EntityCollection<SupplyOrderEntity>();

            var filter = new RelationPredicateBucket(SupplyOrderFields.SupplyOrderNumber == _txtSupplyOrderNumber.Text.Trim());

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count <= 0)
            {
                return;
            }

            _supplyOrderEntity = collection[0];

            var supplyOrderItems = new EntityCollection<SupplyOrderItemEntity>();

            DALHelper.FetchCollection
                (supplyOrderItems, new RelationPredicateBucket(SupplyOrderItemFields.SupplyOrderId == _supplyOrderEntity.Id));

            var docs = new ExtendedDataContext().ExamineDocs.Where(t => t.SupplyOrderId == _supplyOrderEntity.Id).ToList();
            var acceptedDocs = new ExtendedDataContext().ExamineDocs.Where(t => t.SupplyOrderId == _supplyOrderEntity.Id && t.IsAccepted.HasValue && t.IsAccepted.Value).ToList();

            var items = supplyOrderItems.Select(x =>
                                                new ExamineDocView
                                                    {
                                                        ItemId = x.ItemId,
                                                        ItemName = Business.GetItemDetails(x.ItemId).Rows[0]["Name"],
                                                        Quantity = x.Quantity,
                                                        QuantityWeight = x.Quantity * decimal.Parse(Business.GetItemDetails(x.ItemId).Rows[0]["Weight"].ToString()),
                                                        Vendor = Business.GetSupplyOrderSupplierName(_supplyOrderEntity.Id),
                                                        Comments = Business.GetItemDescription(x.ItemId),
                                                        Unit = Business.GetItemDetails(x.ItemId).Rows[0]["Unit"],
                                                        LastExaminedAcceptedQuantity = (acceptedDocs != null && acceptedDocs.Count > 0) ?
                                                                            acceptedDocs.SelectMany(t => t.ExamineDocItems
                                                                         .Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0,
                                                        LastExaminedQuantity = (docs != null && docs.Count > 0) ?
                                                        docs.SelectMany(t => t.ExamineDocItems.Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0
                                                    }).ToList();

            _dgvItems.DataSource = items;
            _dtpSupplyOrderDate.Value = _supplyOrderEntity.Date;

            var supplierCollection = new EntityCollection<SupplierEntity>();
            var supplierFilter = new RelationPredicateBucket(SupplierFields.Id == _supplyOrderEntity.SupplierId);
            DALHelper.FetchCollection(supplierCollection, supplierFilter);
            _txtVendor.Text = supplierCollection != null && supplierCollection.Count > 0 ? supplierCollection[0].Name : "";

            var projectfilter = new RelationPredicateBucket(ProjectFields.Id == _supplyOrderEntity.ProjectId);
            EntityCollection<ProjectEntity> project = new EntityCollection<ProjectEntity>();
            DALHelper.FetchCollection(project, projectfilter);
            _txtProject.Text = project != null && project.Count > 0 ? project[0].Name : "";
        }

        private void SearchSupplyOrder()
        {
            var filter = new RelationPredicateBucket();
            filter.Relations.Add(SupplyOrderEntity.Relations.ProjectEntityUsingProjectId);

            var searchForm = new SearchSupplyOrderForm(SupplyOrderFields.SupplyOrderNumber, SupplyOrderFields.ProjectId, SupplyOrderFields.Date, filter, null);
            if (searchForm.ShowDialog() == DialogResult.OK)
            {
                _txtSupplyOrderNumber.Text = searchForm.SelectedNumber;
                RetrieveOrder();
            }
        }

        private void SetWeightAfterExamine(decimal quantityWeight, decimal quantity, decimal quantityAfterExamine, int index)
        {
            var weight = quantityWeight / quantity;

            _dgvItems.Rows[index].Cells["_colQuantityAfterExamineWeight"].Value = weight * quantityAfterExamine;
        }

        /// <summary>
        /// Disable changing to examine doc or deleting it, if the examine doc is used with Ezn Edafa
        /// </summary>
        /// <returns></returns>
        private void ToggleGridEditing()
        {
            if (_examineDoc == null) return;
            bool readOnly = _examineDoc.IsUsedInDepositTransaction.HasValue && _examineDoc.IsUsedInDepositTransaction.Value ?
                            true :
                            false;

            foreach (DataGridViewColumn column in _dgvItems.Columns)
            {
                column.ReadOnly = readOnly;
            }

            //dtpDate.Enabled = !readOnly;
            //rBtnAcceptItems.Enabled = !readOnly;
            //rBtnRefuseItems.Enabled = !readOnly;
            //rBtnMatched.Enabled = !readOnly;
            //rBtnNotMatched.Enabled = !readOnly;
            _lblMsg.Visible = readOnly;
            SaveBtn.Enabled = !readOnly;
            _btnDelete.Enabled = !readOnly;
        }

        private void RetrieveRequest()
        {
            if (string.IsNullOrEmpty(_txtTransferRequest.Text.Trim()))
                return;

            var collection = new EntityCollection<TransferRequestEntity>();

            var filter = new RelationPredicateBucket(TransferRequestFields.RequestNumber == _txtTransferRequest.Text.Trim());

            DALHelper.FetchCollection(collection, filter);

            if (collection.Count <= 0)
            {
                return;
            }

            _transferRequestEntity = collection[0];

            var transferRequestItems = new EntityCollection<TransferRequestItemEntity>();

            DALHelper.FetchCollection(transferRequestItems, new RelationPredicateBucket
                (TransferRequestItemFields.TransferRequestId == _transferRequestEntity.Id));

            var docs = new ExtendedDataContext().ExamineDocs.Where(t => t.TransferRequestId == _transferRequestEntity.Id).ToList();
            var acceptedDocs = new ExtendedDataContext().ExamineDocs.Where(t => t.TransferRequestId == _transferRequestEntity.Id && t.IsAccepted.HasValue && t.IsAccepted.Value).ToList();

            var items = transferRequestItems.Select(x =>
                                                new ExamineDocView
                                                {
                                                    ItemId = x.ItemId,
                                                    ItemName = Business.GetItemDetails(x.ItemId).Rows[0]["Name"],
                                                    Quantity = x.Quantity,
                                                    QuantityWeight = x.Quantity * decimal.Parse(Business.GetItemDetails(x.ItemId).Rows[0]["Weight"].ToString()),
                                                    Vendor = "-",
                                                    Comments = Business.GetItemDescription(x.ItemId),
                                                    Unit = Business.GetItemDetails(x.ItemId).Rows[0]["Unit"],
                                                    LastExaminedAcceptedQuantity = (acceptedDocs != null && acceptedDocs.Count > 0) ?
                                                                        acceptedDocs.SelectMany(t => t.ExamineDocItems
                                                                     .Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0,
                                                    LastExaminedQuantity = (docs != null && docs.Count > 0) ?
                                                    docs.SelectMany(t => t.ExamineDocItems.Where(a => a.ItemId == x.ItemId)).Sum(y => y.Quantity) : 0
                                                }).ToList();

            _dgvItems.DataSource = items;
            _dtpTransferDate.Value = _transferRequestEntity.Date;

            SetProjectsAndStores();
        }

        private void SetProjectsAndStores()
        {
            var fromProj = Business.GetProjectById(_transferRequestEntity.ProjectId);
            _txtFromProject.Text = fromProj != null
                                            ? fromProj.Name
                                            : string.Empty;

            var toProj = _transferRequestEntity.ToProjectId != null
                             ? Business.GetProjectById(_transferRequestEntity.ToProjectId.Value)
                             : null;

            _txtToProject.Text = toProj != null
                                            ? toProj.Name
                                            : string.Empty;

            var fromStore = Business.GetStoreDetails(_transferRequestEntity.FromStoreId);
            _txtFromStore.Text = fromStore != null
                                            ? fromStore.Rows[0][2].ToString()
                                            : string.Empty;
            var toStore = Business.GetStoreDetails(_transferRequestEntity.ToStoreId);
            _txtToStore.Text = toStore != null
                                            ? toStore.Rows[0][2].ToString() // name in first row
                                            : string.Empty;
        }

        #endregion
    }
}